import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:flutter_lottie/flutter_lottie.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:recorder_wav/recorder_wav.dart';

import 'action.dart';
import 'state.dart';

Widget buildView(
    AnswerEditState state, Dispatch dispatch, ViewService viewService) {
  var border = OutlineInputBorder(
    borderSide: BorderSide(
      color: Colors.white,
    ),
  );

  LottieController lottieController;
  void onViewCreated(LottieController controller) {
    lottieController = controller;

    // Listen for when the playback completes
    lottieController.onPlayFinished.listen((bool animationFinished) {
      print("Playback complete. Was Animation Finished? " +
          animationFinished.toString());
    });
  }

  List<Widget> preview() {
    var children = <Widget>[];

    if (state.photos != null &&
        state.currentOcrIndex >= 0 &&
        state.currentOcrIndex < state.photos.length) {
      children.add(Opacity(
          opacity: 0.9,
          child: Container(
            color: Colors.black87,
          )));
      children.add(Center(
          child: AssetThumb(
        asset: state.photos[state.currentOcrIndex],
        width: MediaQuery.of(viewService.context).size.width.toInt(),
        height: (MediaQuery.of(viewService.context).size.width / 3 * 4).toInt(),
      )));
      children.add(
        Center(
            child: LottieView.fromFile(
          filePath: "assets/lotties/camera_scanning.json",
          autoPlay: true,
          loop: true,
          reverse: true,
          onViewCreated: onViewCreated,
        )),
      );
    }
    return children;
  }

  var recording = false;
  var isTitle = true;

  Widget bottomButtons(StateSetter setState) {
    return Column(children: <Widget>[
      recording
          ? Container(
              width: 100,
              height: 100,
              child: LottieView.fromFile(
                filePath: "assets/lotties/sound_visualizer.json",
                autoPlay: true,
                loop: true,
                reverse: true,
                onViewCreated: onViewCreated,
              ))
          : Container(height: 0.0, width: 0.0),
      Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          GestureDetector(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset("assets/images/camera2.png",
                    width: 56, height: 56, fit: BoxFit.cover),
                Text('拍照'),
              ],
            ),
            onTap: () {
              dispatch(AnswerEditActionCreator.focus(false));
              dispatch(AnswerEditActionCreator.onTakePhoto());
            },
          ),
          GestureDetector(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset("assets/images/voice3.png",
                    width: 56, height: 56, fit: BoxFit.cover),
                Text('语音'),
              ],
            ),
            onTapDown: (detail) {
              setState(() {
                recording = true;
                isTitle = state.focusNodeTitle.hasFocus;
              });
              RecorderWav.startRecorder();
            },
            onTapUp: (detail) {
              setState(() {
                recording = false;
              });
              RecorderWav.StopRecorder();
            },
            onLongPressUp: () async {
              setState(() {
                recording = false;
              });
              var filePath = await RecorderWav.StopRecorder();
              dispatch(AnswerEditActionCreator.focus(isTitle));
              dispatch(AnswerEditActionCreator.onVoiceAi(filePath));
            },
          ),
          GestureDetector(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset("assets/images/ai.png",
                    width: 56, height: 56, fit: BoxFit.cover),
                Text('AI批改'),
              ],
            ),
            onTap: () => dispatch(AnswerEditActionCreator.onAiSubmit()),
          ),
          GestureDetector(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset("assets/images/submit_btn.png",
                    width: 56, height: 56, fit: BoxFit.cover),
                Text('提交'),
              ],
            ),
            onTap: () => dispatch(AnswerEditActionCreator.onSubmit()),
          ),
        ],
      )
    ]);
  }

  return Scaffold(
    appBar: new AppBar(
      centerTitle: true,
      elevation: 2.0,
      title: new Text(
        "作文",
        style: TextStyle(color: Colors.black54, fontSize: 18),
      ),
      actions: <Widget>[
        FlatButton(
          child: Text('作文要求'),
          onPressed: () => dispatch(AnswerEditActionCreator.onDemand()),
        )
      ],
    ),
    body: SafeArea(
      child: Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5.0),
          ),
          margin: EdgeInsets.all(10),
          child: Stack(
            children: <Widget>[
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Container(
                  height: 5,
                  decoration: BoxDecoration(
                    color: Colors.blue,
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(5),
                        topRight: Radius.circular(5)),
                  ),
                ),
              ),
              Positioned(
                top: 0,
                right: 0,
                height: 50,
                child: Image.asset("assets/images/qubiezhen.png"),
              ),
              SingleChildScrollView(
                  padding: EdgeInsets.all(10),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Text(
                        '小IN会自动保存您的作文～',
                        style: TextStyle(color: Colors.grey),
                      ),
                      SizedBox(height: 10),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        child: TextField(
                          maxLines: 1,
                          autofocus: true,
                          controller: state.titleEditController,
                          focusNode: state.focusNodeTitle,
                          decoration: InputDecoration(
                            contentPadding: EdgeInsets.all(8),
                            hintText: '请输入作文标题',
                            hintStyle: TextStyle(color: Colors.blue),
                            enabledBorder: border,
                            focusedBorder: border,
                          ),
                          onChanged: (input) {},
                        ),
                      ),
                      SizedBox(height: 10),
                      Divider(height: 1),
                      SizedBox(height: 10),
                      Padding(
                          padding: EdgeInsets.symmetric(horizontal: 10),
                          child: TextField(
                            maxLines: null,
                            minLines: 8,
                            controller: state.contentEditController,
                            focusNode: state.focusNodeContent,
                            decoration: InputDecoration(
                              contentPadding: EdgeInsets.all(8),
                              hintText: '请输入作文内容',
                              hintStyle: TextStyle(color: Colors.blue),
                              enabledBorder: border,
                              focusedBorder: border,
                            ),
                            onChanged: (input) {},
                          )),
                      SizedBox(height: 90),
                    ],
                  )),
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child:
                    StatefulBuilder(builder: (context, StateSetter setState) {
                  return SizedBox(
                      height: recording ? 180 : 80,
                      child: bottomButtons(setState));
                }),
              ),
              Stack(children: preview()),
            ],
          )),
    ),
  );
}
